package com.cy.letcode.link.exchange;

/**
 * 链表交换位置
 * head->1->2->3->4
 * head->1->3->2->4
 * 参考图解
 * https://www.cnblogs.com/lixinjie/p/a-post-help-you-understanding-sinlge-linkedlist-and-never-forget.html
 *
 * @author yuchen
 */
public class LinkedElementExchange {

    public ListNode exchange(ListNode head, int start) {
        if (start == 0) {
            ListNode headNext = head.next;
            head.next = headNext.next;
            headNext.next = head;
            return headNext;
        }
        int index = 0;
        ListNode pre = null;
        ListNode curr = head;
        while (curr != null) {
            if (index == start) {
                break;
            }
            pre = curr;
            curr = curr.next;
            index++;
        }
        if (curr == null || curr.next == null) {
            return head;
        }
        ListNode currNext = curr.next;
        curr.next = currNext.next;
        currNext.next = curr;
        pre.next = currNext;
        return head;
    }

    public static void main(String[] args) {
        ListNode l = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
        ListNode listNode = new LinkedElementExchange().exchange(l, 3);
        while (listNode != null) {
            System.out.print(listNode.val);
            listNode = listNode.next;
        }
    }
}
